package com.ayitubie.refuelweb.rocketmq;

import com.alibaba.fastjson.JSON;
import com.ayitubie.refuelweb.entity.User;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import freemarker.template.Template;

import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;



/**
 * @author: mahd
 * @Date: 2020/4/21 11:05
 * @Description: 消费者监听
 */
@Component
public class MQConsumeMsgListenerProcessor implements MessageListenerConcurrently {
    public static final Logger LOGGER = LoggerFactory.getLogger(MQConsumerConfigure.class);

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    private Configuration freemarkerConfiguration;

    /**
     * 默认msg里只有一条消息，可以通过设置consumeMessageBatchMaxSize参数来批量接收消息
     * 不要抛异常，如果没有return CONSUME_SUCCESS ，consumer会重新消费该消息，直到return CONSUME_SUCCESS
     *
     * @param msgList
     * @param consumeConcurrentlyContext
     * @return
     */
    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgList, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        if (CollectionUtils.isEmpty(msgList)) {
            LOGGER.info("MQ接收消息为空，直接返回成功");
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
        MessageExt messageExt = msgList.get(0);
        LOGGER.info("MQ接收到的消息为：" + messageExt.toString());
        try {
            String topic = messageExt.getTopic();
            String tags = messageExt.getTags();
            String body = new String(messageExt.getBody(), "utf-8");
            User user = JSON.parseObject(messageExt.getBody(), User.class);
            LOGGER.info("MQ消息topic={}, tags={}, 消息内容={}", topic, tags, body);
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); // true表示支持多部分消息

            helper.setSubject("加油宝新增用户");
            helper.setFrom("180432287@qq.com");
            helper.setTo("mhd_001@sina.com");
            helper.setSentDate(new Date());

            // 使用FreeMarker生成邮件正文
            String htmlContent = generateEmailHtml(user);

            // 第二个参数true表示这是HTML内容
            helper.setText(htmlContent, true);

            javaMailSender.send(message);
            // 发送邮件
        } catch (Exception e) {
            LOGGER.error("获取MQ消息内容异常{}", e);
        }

        // TODO 处理业务逻辑
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    private String generateEmailHtml(User user) {
        try {
            Map<String, Object> model = new HashMap<>();
            model.put("user", user);

            Template template = freemarkerConfiguration.getTemplate("email-template.ftl");
            return FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
        } catch (Exception e) {
            // 如果模板渲染失败，回退到原始文本
            return getFallbackText(user);
        }
    }

    private String getFallbackText(User user) {
        return "你好，士官长：\n" +
                "    用户名：" + user.getUserName() + "\n" +
                "    密码：" + user.getPassword() + "\n";
    }
}
